package com.tyz.hellocst.fragment;

import android.app.ActionBar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.tyz.hellocst.AppContext;

import com.tyz.hellocst.R;
import com.tyz.hellocst.activity.GoodsActivity;
import com.tyz.hellocst.adapter.GoodsItemAdapter;
import com.tyz.hellocst.adapter.ImagePaperAdapter;
import com.tyz.hellocst.database.DBOperate;
import com.tyz.hellocst.entity.Goods;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HomePageFragment extends Fragment {
    View view;
    View searchView;
    private ViewPager viewPager;
    private ListView listView;
    private ArrayList<Goods> arrayList;
    private ArrayAdapter<Goods> adapter;
    private EditText editText;
    private ImageView imageView;
    private ImageButton imageButton;
    Cursor cursor;
    String content;
    private Boolean result;
    private DBOperate dbOperate;
    //    用于存放小圆点图片
    private List<ImageView> dotViewList;

    //    用于存放轮播效果图片
    private List<ImageView> list;
    private LinearLayout dotLayout;

    private RelativeLayout relativeLayout;
    private int currentItem = 0;//当前页面

    boolean isAutoPlay = true;//是否自动轮播

    private ScheduledExecutorService scheduledExecutorService;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home_page,container,false);

        dbOperate = new DBOperate(getContext());
        isAutoPlay = AppContext.isViewPagerIsAutoPlay();

        //初始化ListView
        initListView();
        //初始化ViewPager
        initViewPager();
        // 自动轮播
        if (isAutoPlay) {
            startPlay();
        }

        relativeLayout = view.findViewById(R.id.homePage_layout);
        relativeLayout.setVisibility(AppContext.getRelativeLayoutVisibility());

        ImageView imageView = view.findViewById(R.id.homePage_close);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scheduledExecutorService.shutdownNow();
                relativeLayout.setVisibility(View.GONE);
                AppContext.setRelativeLayoutVisibility(View.GONE);
            }
        });

        searchFunction(view);

        return view;
    }

    private void searchFunction(View view) {
        //获取搜索输入框
        searchView = view.findViewById(R.id.titleBar);
        editText = searchView.findViewById(R.id.edittext);
        imageView = searchView.findViewById(R.id.clearIv);
        imageButton = searchView.findViewById(R.id.btn_search);

        imageView.setVisibility(View.GONE);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //把EditText内容设置为空
                editText.setText("");

            }
        });

        //EditText添加监听
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("KKKKKKKKKKKKKKKK"+s.length());
                //如果长度为0
                if (s.length() == 0) {
                    //隐藏“删除”图片
                    imageView.setVisibility(View.GONE);
                    initListView();
                } else {//长度不为0
                    //显示“删除图片”
                    imageView.setVisibility(View.VISIBLE);
                    content = editText.getText().toString().trim();


                }
            }



            @Override
            public void afterTextChanged(Editable s) {

            }


        });



        //ImageButton添加监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果输入框内容为空，提示请输入搜索内容
                if ((content).isEmpty()) {
                    Toast.makeText(getContext(), "请输入您要搜索的内容", Toast.LENGTH_SHORT).show();
                }else{
                    showSearchListView(content);
                    //判断cursor是否为空
                    if (!result) {
                        Toast.makeText(getContext(), "对不起，没有你要搜索的内容", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }


    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 100) {
                viewPager.setCurrentItem(currentItem);
            }
            return false;
        }


    });

    public void initListView() {

        listView = view.findViewById(R.id.homePage_listView);
        arrayList = new ArrayList<>();
        adapter = new GoodsItemAdapter(getContext(), arrayList);
        listView.setAdapter(adapter);

        dbOperate.openDB();
        SQLiteDatabase db = dbOperate.getDb();
        cursor = db.query(dbOperate.getGoodsTableName(),
                null, "goodsState=0", null,
                null, null, "goodsTime DESC");

        arrayList.clear();
        if (cursor.getCount() != 0) {
            cursor.moveToFirst();
            do {
                int bytesIndex =cursor.getColumnIndex("goodsImage");
                byte[] bytes = cursor.getBlob(bytesIndex);
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);

                Goods goods = new Goods();
                int GoodsIdIndex = cursor.getColumnIndex("goodsId");
                goods.setGoodsId(cursor.getString(GoodsIdIndex));
                int GoodsNameIndex = cursor.getColumnIndex("goodsName");
                goods.setGoodsName(cursor.getString(GoodsNameIndex));
                int GoodsTextIndex = cursor.getColumnIndex("goodsText");
                goods.setGoodsText(cursor.getString(GoodsTextIndex));
                goods.setGoodsImage(bitmap);
                int GoodsTimeIndex = cursor.getColumnIndex("goodsTime");
                goods.setGoodsTime(cursor.getString(GoodsTimeIndex));
                int GoodsPriceIndex = cursor.getColumnIndex("goodsPrice");
                goods.setGoodsPrice(cursor.getDouble(GoodsPriceIndex));
                int GoodsOwnerIndex = cursor.getColumnIndex("goodsOwner");
                goods.setGoodsOwner(cursor.getString(GoodsOwnerIndex));
                int GoodsOwnerContactIndex = cursor.getColumnIndex("goodsOwnerContact");
                goods.setGoodsOwnerContact(cursor.getString(GoodsOwnerContactIndex));
                int GoodsStateIndex = cursor.getColumnIndex("goodsState");
                goods.setGoodsState(cursor.getInt(GoodsStateIndex));
                int GoodsBuyersIndex = cursor.getColumnIndex("goodsBuyers");
                goods.setGoodsBuyers(cursor.getString(GoodsBuyersIndex));

                arrayList.add(goods);
                adapter.notifyDataSetChanged();//刷新数据
            } while (cursor.moveToNext());//while

        }//if
        dbOperate.closeDb();
        cursor.close();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String intentGoodsId = (arrayList.get(position)).getGoodsId();
                Intent intent = new Intent(getContext(), GoodsActivity.class);
                intent.putExtra("intentGoodsId", intentGoodsId);
                startActivity(intent);
            }
        });

    }

    public void initViewPager() {
        viewPager = view.findViewById(R.id.homePage_viewPager);
        dotLayout = view.findViewById(R.id.homePage_dotLayout);
        dotLayout.removeAllViews();
        dotViewList = new ArrayList<>();
        list = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            ImageView dotView = new ImageView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ActionBar.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

            params.leftMargin = 15;//设置小圆点的外边距
            params.rightMargin = 15;
            params.height = 40;//设置小圆点的大小
            params.width = 40;

            if (i == 0) {
                dotView.setBackgroundResource(R.drawable.point_pressed);
            } else {
                dotView.setBackgroundResource(R.drawable.point_unpressed);
            }
            dotLayout.addView(dotView, params);
            dotViewList.add(dotView);
        }//上面是动态添加了四个小圆点

        ImageView[] imageView = new ImageView[4];
        int[] resid = new int[]{R.drawable.main_image1, R.drawable.main_image2,
                R.drawable.main_image3, R.drawable.main_image4};

        for (int i = 0; i < 4; i++) {
            imageView[i] = LayoutInflater.from(getContext())
                    .inflate(R.layout.viewpager_item, null)
                    .findViewById(R.id.viewPager_item);
            imageView[i].setBackgroundResource(resid[i]);
            list.add(imageView[i]);

        }//上面是动态添加了四个滚动图片

        ImagePaperAdapter adapter = new ImagePaperAdapter(list);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);

        viewPager.addOnPageChangeListener(new MyPageChangeListener());
    }//initView()

    //显示搜索后的商品列表
    public void showSearchListView(String content) {
        ArrayList<Goods> goods = new ArrayList<>();
        adapter = new GoodsItemAdapter(getContext(), goods);
        goods = dbOperate.searchGoods(adapter,content);
        if(goods==null){
            result = false;
        }else{
            result = true;
            adapter = new GoodsItemAdapter(getContext(), goods);
            listView.setAdapter(adapter);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String intentGoodsId = (arrayList.get(position)).getGoodsId();
                    Intent intent = new Intent(getContext(), GoodsActivity.class);
                    intent.putExtra("intentGoodsId", intentGoodsId);
                    startActivity(intent);
                }
            });
        }
    }


    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
        //根据他的参数说明，第一个参数是执行的任务，第二个参数是第一次执行的间隔，第三个参数是执行任务的周期；
    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % list.size();
                mHandler.sendEmptyMessage(100);
            }
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    System.out.println("手势滑动，空闲中");
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    System.out.println("界面切换中");
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                        System.out.println("滑动到最后一张");
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                        System.out.println("滑动到第一张");
                    }
                    break;
                default:
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            //这里面动态改变小圆点的背景，来实现效果
            currentItem = pos;
            for (int i = 0; i < dotViewList.size(); i++) {
                if (i == pos) {
                    (dotViewList.get(pos)).setBackgroundResource(R.drawable.point_pressed);
                } else {
                    (dotViewList.get(i)).setBackgroundResource(R.drawable.point_unpressed);
                }
            }
        }

    }//private class
}
